<?php

namespace Admin\Frontend\Controllers;

use Helpers\Tool;
use Helpers\Main;
use Helpers\Template;
use Helpers\Assets;
use Admin\Models\log\XhlogCommit;
use Admin\Models\log\XhlogError;
use Admin\Models\log\XhlogApperror;
use Admin\Models\log\XhlogApplocate;
use Helpers\XhException;
use Modules\Power;
use Services\Log\Log;

class LogController extends ControllerBase
{
    /**
     * 后台操作日志列表
     *
     * create by ck 20161021
     */
    public function manageCommitListAction()
    {
        $this->view->pick('log/manageCommitList');
        Assets::easyUI('js/log/manageCommitList.js');
        Main::showNavPosition();
        if (!Power::exist('Log_ManageCommitList')) {
            return $this->sendErrorResponse(403, '无查看权限');
        }
        if (!Template::exists('XHLog_Commit', 'list')) {
            return $this->sendErrorResponse(404, '相关配置文件不存在，请先创建！');
        }
        $listButtonArr = $searchToolbar = [];
//        if (Power::exist('Log_ManageCommitList_Del')) {
//            $listButtonArr[] = ['plain'=>'true', 'id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
//        }
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_submodule', 'label' => ' 子模块： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_operate', 'label' => ' 操作： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_explain', 'label' => ' 说明： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_content', 'label' => ' 内容： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_startTime', 'class' => 'easyui-datebox', 'label' => ' 时间： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_endTime', 'class' => 'easyui-datebox', 'label' => ' ~ '];
        return $this->view->setVar('List', Template::createList('List', 'XHLog_Commit', [
            'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
        ]));
    }

    /**
     * 获取后台操作日志
     *
     * create by ck 20161021
     * modify by ck 20180518
     * modify by ck 20181012
     * modify by ck 20190110    重构
     */
    public function getManageCommitDataAction()
    {
        try {
            $data = Log::getCommitLog($this->request->getPost());
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
//        $submodule = $this->request->getPost('submodule', 'string');
//        $operate = $this->request->getPost('operate', 'string');
//        $explain = $this->request->getPost('explain', 'string');
//        $content = $this->request->getPost('content', 'string');
//        $startDate= $this->request->getPost('startDate', 'string');
//        $endDate  = $this->request->getPost('endDate', 'string');
//
////        $parameters = [
////            'order'      => 'iCommitId DESC',
////            'conditions' => '',
////            'bind' => []
////        ];
////        if ($submodule) {
////            $parameters['conditions'] .= "sSubmodule like :submodule: AND ";
////            $parameters['bind'] += ['submodule' => '%'.$submodule.'%'];
////        }
////        if ($operate) {
////            $parameters['conditions'] .= "sOperate like :operate: AND ";
////            $parameters['bind'] += ['operate' => '%'.$operate.'%'];
////        }
////        if ($explain) {
////            $parameters['conditions'] .= "sExplain like :explain: AND ";
////            $parameters['bind'] += ['explain' => '%'.$explain.'%'];
////        }
////        if ($content) {
////            $parameters['conditions'] .= "mContent like :content: AND";
////            $parameters['bind'] += ['content' => '%'.$content.'%'];
////        }
////        if ($startDate) {
////            $parameters['conditions'] .= "tCreateDate >= '{$startDate}' AND ";
////        }
////        if ($endDate) {
////            $parameters['conditions'] .= "tCreateDate <= '{$endDate}' AND ";
////        }
////        $parameters['conditions'] = rtrim($parameters['conditions'], ' AND ');
////        $data = Main::runModelPage('\\Admin\\Models\\log\\XhlogCommit', $parameters);
//        try {
//            $conditions = [];
//            if ($submodule) {
//                $conditions[] = "sSubmodule like '%{$submodule}%'";
//            }
//            if ($operate) {
//                $conditions[] = "sOperate like '%{$operate}%'";
//            }
//            if ($explain) {
//                $conditions[] = "sExplain like '%{$explain}%'";
//            }
//            if ($content) {
//                $conditions[] = "MATCH(mContent) AGAINST ('*{$content}*' IN BOOLEAN MODE)";
//            }
//            if ($startDate) {
//                $conditions[] = "tCreateDate >= '{$startDate}'";
//            }
//            if ($endDate) {
//                $conditions[] = "tCreateDate <= '{$endDate}'";
//            }
//            if ($conditions) {
//                $conditions = 'WHERE ' . implode(' AND ', $conditions);
//            } else {
//                $conditions = '';
//            }
//            $sql = "SELECT * FROM XHLog_Commit {$conditions} ORDER BY iCommitId DESC";
//            $data = Main::runSqlPage($sql);
//            Main::runUserName($data['rows'], ['iUserId' => 'sUserName']);
//            Main::runUserLogonName($data['rows'], ['iUserId' => 'sLogonName']);
//            //替换操作内容文字为 点击查看
//            foreach ($data['rows'] as $index => $row) {
//                $row['mContent'] = htmlspecialchars($row['mContent']);
//                $data['rows'][$index]['mContent']
//                    = '<a href="javascript:;" onclick="obj.funObj().detail('.$row['mContent'].')">点击查看</a>';
//            }
//            return $this->sendJsonResponse($data);
//        } catch (XhException $e) {
//            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
//        } catch (\Exception $e) {
//            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
//        }
    }

    /**
     * 删除后台操作日志
     *
     * create by ck 20161021
     */
//    public function delManageCommitDataAction()
//    {
//        $this->view->disable();
//        Power::exist('Log_ManageCommitList_Del') or die('（109111013）无删除权限！');
//        $idArr = explode(',', $this->request->getPost('ids', 'string'));
//        XhlogCommit::deleteRecordById($idArr) or die('（109111014）删除失败！');
//        Main::createCommitLog('log', 'ManageCommit', 'del', ['ids' => $idArr], null, '批量删除');
//        echo '删除成功！';
//    }

    /**
     * 平台登陆日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     *
     * create by ck 20190116
     */
    public function platformLoginAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/log/platformLogin.js');
        if (!Power::exist('Log_Login')) {
            return $this->sendErrorResponse(403, '无查看权限');
        }
        $listButtonArr = $searchToolbar = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_startTime', 'class' => 'easyui-datebox', 'label' => '时间： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_endTime', 'class' => 'easyui-datebox', 'label' => ' ~ '];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_item', 'label' => ' 搜索：', 'data' => [
            'lo_uid' => '用户账号',
            'lo_computername' => '设备序列号',
            'lo_mac' => 'MAC地址',
            'lo_ip' => 'IP地址',
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search'];
        return $this->view->setVar('List', Template::createList('list', 'Log_PlatformLogin', [
            'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
        ]));
    }

    /**
     * 获取平台登陆日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20190116
     */
    public function getPlatformLoginAction()
    {
        try {
            $data = Log::getPlatformLoginLog($this->request->getPost());
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 应用错误日志列表
     *
     * create by ck 20161020
     */
    public function appErrorListAction()
    {
        $this->view->pick('log/appErrorList');
        Assets::easyUI('js/log/appErrorList.js');
        Main::showNavPosition();
        if (!Power::exist('Log_AppErrorList')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $searchToolbar = [];
//        if (Power::exist('Log_AppErrorList_Del')) {
//            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
//        }
        $listSearchArr[] = ['type'=>'text', 'id'=>'list_search', 'name'=>'list_search', 'label'=>'搜索： '];
        return $this->view->setVar('List', Template::createList('List', 'XHLog_AppError', [
            'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
        ]));
    }

    /**
     * 获取应用错误日志
     *
     * create by ck 20161020
     * modify by ck 20190114    重构
     */
    public function getAppErrorDataAction()
    {
        try {
            return $this->sendJsonResponse(Log::getErrorLog());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
//        $this->view->disable();
//        $parameters['order'] = 'iAEId DESC';
//        Main::runSearchVagueConditions(
//            $parameters['conditions'],
//            ['iAppCode', 'iErrorCode', 'iUserId', 'sPackName', 'sDeviceId', 'sRequestFun', 'sLogType', 'tCreateDate']
//        );
//        echo Main::runModelPaginator('\\Admin\\Models\\log\\XhlogApperror', $parameters);
    }

    /**
     * 删除应用错误日志
     *
     * create by ck 20161020
     */
//    public function delAppErrorDataAction()
//    {
//        $this->view->disable();
//        Power::exist('Log_AppErrorList_Del') or die('（109111005）无删除权限！');
//        $idArr = explode(',', $this->request->getPost('ids', 'string'));
//        XhlogApperror::deleteRecordById($idArr) or die('（109111006）删除失败！');
//        Main::createCommitLog('log', 'AppError', 'del', ['ids' => $idArr], null, '批量删除');
//        echo '删除成功！';
//    }

    /**
     * 应用定位日志页面
     *
     * create by ck 20161017
     */
//    public function appLocateListAction()
//    {
//        $this->view->pick('log/appLocateList');
//        Assets::easyUI('js/log/appLocateList.js');
//        Main::showNavPosition();
//        Power::exist('Log_AppLocateList') or die(Main::showMessageModal('无查看权限！', 109111001));
//        Template::exists('XHLog_AppLocate', 'list') or die(Main::showMessageModal('相关配置文件不存在，请先创建！', 109111002));
//        $listButtonArr = $searchToolbar = [];
//        if (Power::exist('Log_AppLocateList_Del')) {
//            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
//        }
//        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'name' => 'list_search', 'label' => '搜索： '];
//        $this->view->setVar('List', Template::createList('List', 'XHLog_AppLocate', [
//            'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
//            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
//        ]));
//    }

    /**
     * 获取应用定位日志
     *
     * create by ck 20161017
     */
//    public function getAppLocateDataAction()
//    {
//        $this->view->disable();
//        $parameters['order'] = 'iALId DESC';
//        Main::runSearchVagueConditions($parameters['conditions'], ['iUserId', 'sDeviceId', 'sPackName', 'sLogType', 'mDesc', 'tCreateDate']);
//        echo Main::runModelPaginator('\\Admin\\Models\\log\\XhlogApplocate', $parameters);
//    }

    /**
     * 删除应用定位日志
     *
     * create by ck 20161025
     */
//    public function delAppLocateDataAction()
//    {
//        $this->view->disable();
//        Power::exist('Log_AppLocateList_Del') or die('（109111014）无删除权限！');
//        $idArr = explode(',', $this->request->getPost('ids', 'string'));
//        XhlogApplocate::deleteRecordById($idArr) or die('（109111015）删除失败！');
//        Main::createCommitLog('log', 'Locate', 'del', ['ids' => $idArr], null, '批量删除');
//        echo '删除成功！';
//    }

    /**
     * 后台错误日志列表
     *
     * create by ck 20161021
     */
//    public function manageErrorListAction()
//    {
//        $this->view->pick('log/manageErrorList');
//        Assets::easyUI('js/log/manageErrorList.js');
//        Main::showNavPosition();
//        Power::exist('Log_ManageErrorList') or die(Main::showMessageModal('无查看权限！', 109111007));
//        Template::exists('XHLog_Error', 'list') or die(Main::showMessageModal('相关配置文件不存在，请先创建！', 109111008));
//        $listButtonArr = $searchToolbar = [];
//        if(Power::exist('Log_ManageErrorList_Del')){
//            $listButtonArr[] = ['plain'=>'true', 'id'=>'bt_list_del', 'text'=>'删除', 'icon'=>'fa-trash'];
//        }
//        $listSearchArr[] = ['type'=>'text', 'id'=>'list_search', 'name'=>'list_search', 'label'=>'搜索： '];
//        $this->view->setVar('List', Template::createList('List', 'XHLog_Error', [
//            'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
//            'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
//        ]));
//    }

    /**
     * 获取后台错误日志
     *
     * create by ck 20161021
     */
//    public function getManageErrorDataAction()
//    {
//        $this->view->disable();
//        $parameters['order'] = 'iErrorId DESC';
//        Main::runSearchVagueConditions(
//            $parameters['conditions'],
//            ['sControllerName', 'sMethodName', 'iUserId', 'tCreateDate']
//        );
//        echo Main::runModelPaginator('\\Admin\\Models\\log\\XhlogError', $parameters);
//    }

    /**
     * 删除后台错误日志
     *
     * create by ck 20161021
     */
//    public function delManageErrorDataAction()
//    {
//        $this->view->disable();
//        Power::exist('Log_ManageErrorList_Del') or die('（109111009）无删除权限！');
//        $idArr = explode(',', $this->request->getPost('ids', 'string'));
//        XhlogError::deleteRecordById($idArr) or die('（109111010）删除失败！');
//        Main::createCommitLog('log', 'ManageError', 'del', ['ids' => $idArr], null, '批量删除');
//        echo '删除成功！';
//    }
}
